package com.zy.voteya.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zy.voteya.entity.Items;
import com.zy.voteya.entity.Result;
import com.zy.voteya.entity.Vote;
import com.zy.voteya.mapper.VoteMapper;
import com.zy.voteya.service.BizException;
import com.zy.voteya.service.IVoteService;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LiaoYan
 * @since 2025-09-20
 */
@RestController
@RequestMapping("vote")
public class VoteController {

    @Autowired
    VoteMapper voteMapper;

    @RequestMapping("list")
    public Page<Vote> list(@RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "5") int size){
        // 构建分页对象
        Page<Vote> pg = Page.of(page, size);
        pg = voteMapper.selectPage(pg, null);
        return pg;
    }

    @Autowired
    IVoteService voteService;

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public Result add(@RequestBody @Valid Vote vote, Errors errors){
        // 添加自定义验证
        if(vote.getStartDate() != null && vote.getEndDate() != null &&
            vote.getStartDate().isAfter(vote.getEndDate())){
            errors.rejectValue("endDate", "dateError",
                    "结束时间不能早于开始时间");
        }
        if(vote.getItems()!=null){
            for (int i = 0; i < vote.getItems().size(); i++) {
                Items item = vote.getItems().get(i);
                if(item.getIname().isBlank()){
                    errors.rejectValue("items", "itemEmpty",
                            "第"+(i+1)+"个选项没有输入内容");
                }
            }
        }
        if(errors.hasErrors()){
            throw new BizException("提交数据错误", errors.getAllErrors());
        }
        voteService.create(vote);
        return Result.ok("添加投票题目成功!", null);
    }

    @RequestMapping("findById")
    public Vote findById(int id){
        return voteMapper.findById(id);
    }
    
    /**
     * 获取投票结果数据
     * @param vid 投票ID
     * @return 投票结果数据
     */
    @RequestMapping("voteResults")
    public Result getVoteResults(@RequestParam Integer vid) {
        List<Map<String, Object>> results = voteService.getVoteResults(vid);
        Integer totalVotes = voteService.getTotalVotes(vid);
        
        Map<String, Object> response = new java.util.HashMap<>();
        response.put("results", results);
        response.put("totalVotes", totalVotes);
        
        return Result.ok("success", response);
    }
}
